package com.example.musicserver.service;

import com.example.musicserver.mapper.LoveMusicMapper;
import com.example.musicserver.model.Music;
import com.example.musicserver.model.User;
import com.example.musicserver.tools.Constant;
import com.example.musicserver.tools.ResponseBodyMessage;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Lenovo
 * Date: 2022-08-11
 * Time: 12:15
 */
@Service
public class LoveMusicService {
    @Resource
    private LoveMusicMapper loveMusicMapper;
    public ResponseBodyMessage<Boolean> insertLoveMusic(@RequestParam String id, HttpServletRequest request){
        int musicId = Integer.parseInt(id);

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();

        Music music = loveMusicMapper.findLoveMusicByMusicIdAndUserId(userId,musicId);

        if(music != null){
            boolean flg = loveMusicMapper.deleteLoveMusic(userId,musicId);
            if(flg){
                return new ResponseBodyMessage<>(1,"取消收藏成功",true);
            }else{
                return new ResponseBodyMessage<>(-1,"取消收藏失败",false);
            }
        }else{
            boolean ret = loveMusicMapper.insertLoveMusic(userId,musicId);

            if(!ret){
                return new ResponseBodyMessage<>(-1,"当前歌曲收藏失败",false);
            }else{
                return new ResponseBodyMessage<>(1,"当前歌曲成功收藏",true);
            }
        }
    }

    public ResponseBodyMessage<List<Music>> findLoveMusic(@RequestParam(required = false) String musicName, HttpServletRequest request){
        HttpSession session = request.getSession(false);

        User user = (User) session.getAttribute(Constant.USERINFO_SESSION_KEY);
        int id = user.getId();

        List<Music> music = null;

        if(musicName == null){
            music = loveMusicMapper.findLoveMusic(id);
        }else{
            music = loveMusicMapper.findLoveMusicByName(musicName,id);
        }

        return new ResponseBodyMessage<>(1,"查询成功",music);

    }

    public ResponseBodyMessage<Boolean> deletelovemusicById(@RequestParam String id,HttpServletRequest request){
        int musicId = Integer.parseInt(id);
//没有session不创建
        HttpSession httpSession = request.getSession(false);
        User user = (User)httpSession.getAttribute(Constant.USERINFO_SESSION_KEY);
        int userId = user.getId();
        boolean flg = loveMusicMapper.deleteLoveMusic(userId,musicId);
        if(flg){
            return new ResponseBodyMessage<>(1,"取消收藏成功",true);
        }else{
            return new ResponseBodyMessage<>(-1,"取消收藏失败",false);
        }
    }
}
